import { Ctx, Next, YeeApi } from '../types';
import { router } from '../router/index';
import { apiMapIndex } from '../lib/registerHandleApi';

/**
 * 中间件验证路由
 * @export
 * @param {Ctx} ctx
 * @param {Next} next
 */
export async function validatorRouterLiving(ctx: Ctx, next: Next) {

  if(ctx.method == 'OPTIONS') {
    await next();
  }else{
    const { path } = ctx;
    let routerPath: Array<string> = [];
    router.match(path, ctx.method).pathAndMethod.map(route => {
      if (route.path != '(.*)') {
        route.methods.map(method => {
          routerPath.push(`${method.toLowerCase()} ${route.path}`);
        })
      }
    });
    
    try {
      const routerliving = getRouterLiving(routerPath);  
      ctx.routerliving = routerliving;
    } catch (error) {
      ctx.throw(404, ctx.error(error.message));
    }

    await next();
  }
  
}

/**
 * 获取路由实例
 * @export
 * @param {string} name
 * @returns {Api}
 */
export function getRouterLiving(routers: Array<string>): YeeApi {
  let routePath = null;
  routers.map(path => {
    if(apiMapIndex.has(path)) {
      routePath = path;
    }
  });

  if(routePath == null) {
    throw new Error('router living not fond');
  }
  return apiMapIndex.get(routePath);
}